package com.qk.management.service.impl;

import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.dto.business.BusinessTrackRecordDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.service.BusinessTrackRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商机跟进记录Service实现类
 */
@Service
@Transactional
public class BusinessTrackRecordServiceImpl implements BusinessTrackRecordService {

    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public void addTrackRecord(BusinessTrackRecordDTO dto) {
        // 参数校验
        if (dto == null || dto.getId() == null ) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        // 验证商机是否存在
        Business business = businessMapper.selectById(dto.getId());
        if (business == null) {
            throw new CommonException(ParamEnum.PARAM_ERROR);
        }

        // 创建跟进记录
        BusinessTrackRecord trackRecord = new BusinessTrackRecord();
        trackRecord.setBusinessId(dto.getId());
        trackRecord.setTrackStatus(Integer.valueOf(dto.getTrackStatus()));
        // 将字符串数组转换为逗号分隔的字符串存储
        if (dto.getKeyItems() != null && !dto.getKeyItems().isEmpty()) {
            trackRecord.setKeyItems(String.join(",", dto.getKeyItems()));
        }
        trackRecord.setNextTime(dto.getNextTime());
        trackRecord.setRecord(dto.getRecord());
        trackRecord.setUserId(CurrentUserContextHolders.get());
        trackRecord.setCreateTime(LocalDateTime.now());

        // 保存跟进记录
        businessTrackRecordMapper.insert(trackRecord);

        // 更新商机状态为跟进中
        business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        business.setNextTime(dto.getNextTime());
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.updateById(business);
    }



}